// merchants/addProject/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    title: '',
    projectType: 1,//1 充值卡,2 次卡,3 时效卡
    days: '',
    showRule: false,
    ratio: '',//充值卡的支付比例
    remark: '',
    detailpics: [],
    isEditor: 0
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      this.setData({
        id: options.id,
      })
      this.getProject(options.id);
      if (options.isEditor){
        this.setData({
          isEditor: options.isEditor
        })
      }
    }
  },

// 新增消费卡
  addOrUpdateProject: function(){
    let that = this;
    let days = that.data.days;
    let discount = that.data.ratio;
    let detailpics = that.data.detailpics;
    if (detailpics.length > 0) {
      for (var i = 0; i < detailpics.length; i++) {
        var Index = detailpics[i].lastIndexOf('l/');
        detailpics[i] = detailpics[i].substr(Index + 2, detailpics[i].length);
      }
    }
    detailpics = detailpics.toString();
    if(!that.data.title){
      that.checkWrite('请输入消费卡名！');
      return
    }
    if(days==''){
      days = 365;
    }
    if (discount == '') {
      discount = 100;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true,
    });
    wx.request({
      url: app.globalData.host + '/api/Coupon/AddOrUpdateCardItem',
      data:{
        uid: app.globalData.userInfo.Uid,
        name: that.data.title,
        cardType: that.data.projectType,
        days: days,
        id: that.data.id,
        discount: discount,
        remark: that.data.remark,
        detailPics: detailpics
      },
      method: 'POST',
      success:function(res){
        wx.hideLoading();
        if(res.data.Code==0){
          wx.showToast({
            title: '添加成功',
            duration: 2000,
          })
          wx.navigateBack({
            delta:1
          })
        }else{
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  // 消费卡信息
  getProject: function(id){
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/Coupon/GetCardItem?id=' + id,
      success: function(res){
        if (res.data.Code == 0){
          var detailpics = res.data.Data.DetailPics;
          var list = [];
          if (detailpics != '') {
            var newDetailPics = detailpics.split(",");
            for (let i = 0; i < newDetailPics.length; i++) {
              list[i] = 'https://static.711688.net.cn/upload/coupondetail/' + newDetailPics[i];
            }
          }
          that.setData({
            title: res.data.Data.Name,
            projectType: res.data.Data.CardType,
            days: res.data.Data.Days,
            ratio: res.data.Data.Discount,
            remark: res.data.Data.Remark,
            detailpics: list
          })
        }else{
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },
  //填写判断
  checkWrite: function (str) {
    wx.showModal({
      title: '提示',
      content: str,
      showCancel: false
    })
  },

  clickRule: function(){
    this.setData({
      showRule: !this.data.showRule
    })
  },
  /**
 * 长按删除详细图片
 */
  deleteDetailPic: function (e) {
    var that = this;
    var newPics = that.data.detailpics;
    newPics.splice(e.currentTarget.dataset.index, 1);
    that.setData({
      detailpics: newPics
    })
  },
  /**
   * 上传详细图片
   */

  uploadDetailImage: function (e) { //这里是选取图片的方法
    var that = this;
    var detailPics = [];
    detailPics = that.data.detailpics
    var pics = [];
    if (detailPics.length >= 6) {
      wx.showToast({
        title: '最多选择6张！',
      })
      return;
    }
    wx.chooseImage({
      count: 6, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        var imgs = res.tempFilePaths;
        for (var i = 0; i < imgs.length; i++) {
          pics.push(imgs[i])
        }
        that.uploadimgs({
          url: app.globalData.host + '/api/tool/upload?operation=uploadcouponimage', //这里是你图片上传的接口
          path: pics, //这里是选取的图片的地址数组
        });
      },
    })
  },
  //多张图片上传
  uploadimgs: function (data) {
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: data.url,
      filePath: data.path[i],
      name: 'fileData',
      formData: null,
      success: (resp) => {
        wx.hideLoading();
        success++;
        var str = resp.data
        var pic = JSON.parse(str);
        var pic_name = 'https://static.711688.net.cn/upload/coupondetail/' + pic.Data;
        var detailpics = that.data.detailpics;
        detailpics.push(pic_name);
        that.setData({
          detailpics: detailpics
        })
      },
      fail: (res) => {
        fail++;
        console.log('fail:' + i + "fail:" + fail);
      },
      complete: () => {
        i++;
        if (i == data.path.length) { //当图片传完时，停止调用     
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.uploadimgs(data);
        }
      }
    });
  },
  //商品详情图片预览
  preViewDetailsImg: function (e) {
    let list = this.data.detailpics;
    let src = e.currentTarget.dataset.src;
    let imgs = [];
    for (let i = 0; i < list.length; i++) {
      imgs.push(list[i]);
    }
    imgs.join(",");
    wx.previewImage({
      current: src,
      urls: imgs,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  bindtitle: function(e){
    this.setData({
      title: e.detail.value
    })
  },
  selectType: function(e){
    this.setData({
      projectType: e.currentTarget.dataset.type
    })
  },
  binddays: function(e){
    this.setData({
      days: e.detail.value
    })
  },
  bindratio: function (e) {
    this.setData({
      ratio: e.detail.value
    })
  },
  bindDescVal: function (e) {
    this.setData({
      remark: e.detail.value
    })
  }
})